package utils

import (
	"bytes"
	"http_monitor/single"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

// http request and serialize results.
func HttpRequest(requestUrl string, timeout int64, method string, data string) (result string, doTime int64, code int, err error) {

	reembody := bytes.NewBuffer([]byte(data))
	println(requestUrl)
	req, err := http.NewRequest(method, requestUrl, reembody)
	if err != nil {
		// handle error
	}

	netTransport := &http.Transport{
		//Proxy: http.ProxyFromEnvironment,
		MaxIdleConnsPerHost: 10, //每个host最大空闲连接
	}
	if single.GetInstance().Proxy != "null" {
		proxy, err := url.Parse(single.GetInstance().Proxy)
		if err != nil {
			println(err)
		} else {
			netTransport.Proxy = http.ProxyURL(proxy)
		}

	}

	client := &http.Client{
		Timeout:   time.Duration(timeout) * time.Millisecond, //毫秒
		Transport: netTransport,
	}
	//设置请求头
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	//发送请求
	start := time.Now()
	resp, err := client.Do(req)
	doTime = time.Since(start).Milliseconds()
	//关闭请求

	if err == nil {

		body, _ := ioutil.ReadAll(resp.Body)
		code = resp.StatusCode
		defer resp.Body.Close()
		result = string(body)
		//var value string
		//err = json.NewDecoder(resp.Body).Decode(value)
		//err = json.Unmarshal(body, &result)
	} else {
		doTime = -5000
	}
	return

}
